package com.breaktian.assemble.security.des;

import java.nio.charset.Charset;

/**
 * Created by keke.tian on 2018/4/24.
 */

public class DesUtil {

    /**
     * 加密
     * @param srcStr
     * @param charset
     * @param sKey
     * @return
     */
    public static String encrypt(String srcStr, Charset charset, String sKey) {
        byte[] src = srcStr.getBytes(charset);
        byte[] buf = Des.encrypt(src, sKey);
        return Des.parseByte2HexStr(buf);
    }

    /**
     * 解密
     *
     * @param hexStr
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String hexStr, Charset charset, String sKey) {
        String result = "";
        try {
            byte[] src = Des.parseHexStr2Byte(hexStr);
            byte[] buf = Des.decrypt(src, sKey);
            result = new String(buf, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 加密
     * @param srcStr
     * @param sKey
     * 默认是utf-8编码
     * @return
     */
    public static String encrypt(String srcStr, String sKey) {
        Charset charset = Charset.forName("UTF-8");
        byte[] src = srcStr.getBytes(charset);
        byte[] buf = Des.encrypt(src, sKey);
        return Des.parseByte2HexStr(buf);
    }

    /**
     * 解密
     *
     * @param hexStr
     * @param sKey
     * 默认是utf-8编码
     * @return
     * @throws Exception
     */
    public static String decrypt(String hexStr, String sKey) {
        String result = "";
        try {
            Charset charset = Charset.forName("UTF-8");
            byte[] src = Des.parseHexStr2Byte(hexStr);
            byte[] buf = Des.decrypt(src, sKey);
            result = new String(buf, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    public static void main(String[] args) {
        String SKEY = "abcdefgh";
        Charset CHARSET = Charset.forName("gb2312");
        // 待加密内容
        String str = "测试内容，今天周五";
        String encryptResult = DesUtil.encrypt(str, SKEY);
        System.out.println(encryptResult);
        // 直接将如上内容解密
        String decryResult = "";
            decryResult = DesUtil.decrypt(encryptResult, SKEY);
        System.out.println(decryResult);
    }

}
